package com.rao.core.aop;

import com.rao.entity.VO.CommonResponseVO;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice(basePackages = "com.rao.controller")
public class ControllerAdvice {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = Exception.class)
    public CommonResponseVO exceptionHandler(Exception exception) {
        if (exception instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException e = (MethodArgumentNotValidException) exception;
            Map<String, String> collect =
                    e.getBindingResult().getFieldErrors().stream()
                            .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return CommonResponseVO.fail(CommonResponseVO.FAIL_STATUS, "用户参数错误", collect);
        } else {
            return CommonResponseVO.fail("系统错误:" + exception.getMessage());
        }
    }
}
